package hotel.base.oversea.utils;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author HuangT
 * @Date 2020/10/14 10:20
 */
public class RequestXmlUtil {

    /**
     * <H1>获取xml数据</H1>
     *
     * @param request 实体对象
     * @return java.lang.String
     * @author HuangT
     * @Date 2020/10/14 10:25
     */
    public static String getStringData(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
            String line = null;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != rd) {
                    rd.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    /**
     * <H1>Element转String</H1>
     *
     * @param document	实体对象
     * @return java.lang.String
     * @author HuangT
     * @Date 2020/10/14 17:44
    */
    public static String doc2String(Element document)
    {
        String s = "";
        try
        {
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();
            Source source = new DOMSource(document);
            StringWriter out = new StringWriter();
            StreamResult output = new StreamResult(out);
            transformer.transform(source, output);
            out.flush();
            s = out.toString();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        return s;
    }


    /**
     * <H1>解析XML-IO流 ，获取Document 对象，以及Document对象 的根节点</H1>
     *
     * @param inputStream	实体对象
     * @return org.w3c.dom.Element
     * @author HuangT
     * @Date 2020/10/14 17:58
    */
    public static Element getRootElementFromIs(InputStream inputStream)  {
        if(inputStream == null){
            return  null;
        }
        /*
         * javax.xml.parsers 包中的DocumentBuilderFactory用于创建DOM模式的解析器对象 ，
         * DocumentBuilderFactory是一个抽象工厂类，它不能直接实例化，但该类提供了一个newInstance方法 ，
         * 这个方法会根据本地平台默认安装的解析器，自动创建一个工厂的对象并返回。
         */
        Element root = null;
        try {
            //2-调用 DocumentBuilderFactory.newInstance() 方法得到创建 DOM 解析器的工厂
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            //3-调用工厂对象的 newDocumentBuilder方法得到 DOM 解析器对象。
            DocumentBuilder docBuilder = factory.newDocumentBuilder();
            //4-调用 DOM 解析器对象的 parse() 方法解析 XML 文档，得到代表整个文档的 Document 对象，进行可以利用DOM特性对整个XML文档进行操作了。
            Document doc = docBuilder.parse(inputStream);
            //5-得到 XML 文档的根节点
            root = doc.getDocumentElement();
        } catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
        } finally {
            //6-关闭流
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return root;
    }

    // 将element转换成字符串
    public static String convertElemToSVG(Element element) {
        TransformerFactory transFactory = TransformerFactory.newInstance();
        String elementStr = null;
        try {
            Transformer transformer = transFactory.newTransformer();
            StringWriter buffer = new StringWriter();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.transform(new DOMSource(element), new StreamResult(buffer));
            elementStr = buffer.toString();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        return elementStr;
    }
}
